package com.nbcio.pm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.core.utils.MapstructUtils;
import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.pm.domain.PmTeam;
import com.nbcio.pm.domain.bo.PmTeamBo;
import com.nbcio.pm.domain.vo.PmTeamVo;
import com.nbcio.pm.mapper.PmTeamMapper;
import com.nbcio.pm.service.IPmTeamService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 团队管理Service业务层处理
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmTeamServiceImpl implements IPmTeamService {

    private final PmTeamMapper baseMapper;

    /**
     * 查询团队管理
     */
    @Override
    public PmTeamVo queryById(Long teamId) {
        return baseMapper.selectVoById(teamId);
    }

    /**
     * 查询团队管理列表
     */
    @Override
    public TableDataInfo<PmTeamVo> queryPageList(PmTeamBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PmTeam> lqw = buildQueryWrapper(bo);
        Page<PmTeamVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询团队管理列表
     */
    @Override
    public List<PmTeamVo> queryList(PmTeamBo bo) {
        LambdaQueryWrapper<PmTeam> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PmTeam> buildQueryWrapper(PmTeamBo bo) {
        Map<String, Object> params = bo.getParams();
        if (params == null) {
            params = new HashMap<>();
        }
        LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTeamName()), PmTeam::getTeamName, bo.getTeamName());
        lqw.eq(StringUtils.isNotBlank(bo.getTeamCode()), PmTeam::getTeamCode, bo.getTeamCode());
        lqw.eq(StringUtils.isNotBlank(bo.getTeamType()), PmTeam::getTeamType, bo.getTeamType());
        lqw.eq(StringUtils.isNotBlank(bo.getTeamStatus()), PmTeam::getTeamStatus, bo.getTeamStatus());
        lqw.eq(bo.getTeamLeaderId() != null, PmTeam::getTeamLeaderId, bo.getTeamLeaderId());
        lqw.eq(bo.getParentTeamId() != null, PmTeam::getParentTeamId, bo.getParentTeamId());
        lqw.orderByAsc(PmTeam::getSortOrder).orderByDesc(PmTeam::getCreateTime);
        return lqw;
    }

    /**
     * 新增团队管理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PmTeamBo bo) {
        PmTeam add = MapstructUtils.convert(bo, PmTeam.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTeamId(add.getTeamId());
        }
        return flag;
    }

    /**
     * 修改团队管理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(PmTeamBo bo) {
        PmTeam update = MapstructUtils.convert(bo, PmTeam.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmTeam entity) {
        // 校验团队编码唯一性
        if (StringUtils.isNotBlank(entity.getTeamCode())) {
            LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
            lqw.eq(PmTeam::getTeamCode, entity.getTeamCode());
            if (entity.getTeamId() != null) {
                lqw.ne(PmTeam::getTeamId, entity.getTeamId());
            }
            long count = baseMapper.selectCount(lqw);
            if (count > 0) {
                throw new RuntimeException("团队编码已存在");
            }
        }
        
        // 校验团队名称唯一性
        if (StringUtils.isNotBlank(entity.getTeamName())) {
            LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
            lqw.eq(PmTeam::getTeamName, entity.getTeamName());
            if (entity.getTeamId() != null) {
                lqw.ne(PmTeam::getTeamId, entity.getTeamId());
            }
            long count = baseMapper.selectCount(lqw);
            if (count > 0) {
                throw new RuntimeException("团队名称已存在");
            }
        }
    }

    /**
     * 批量删除团队管理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 校验团队是否有关联数据
            // TODO: 检查团队是否有关联的项目、成员等
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据团队编码查询团队
     */
    @Override
    public PmTeamVo queryByTeamCode(String teamCode) {
        LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeam::getTeamCode, teamCode);
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 根据团队负责人查询团队列表
     */
    @Override
    public List<PmTeamVo> queryByTeamLeader(Long teamLeaderId) {
        LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeam::getTeamLeaderId, teamLeaderId);
        lqw.orderByAsc(PmTeam::getSortOrder);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据团队类型查询团队列表
     */
    @Override
    public List<PmTeamVo> queryByTeamType(String teamType) {
        LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeam::getTeamType, teamType);
        lqw.orderByAsc(PmTeam::getSortOrder);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 检查团队编码是否唯一
     */
    @Override
    public Boolean checkTeamCodeUnique(String teamCode, Long teamId) {
        LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeam::getTeamCode, teamCode);
        if (teamId != null) {
            lqw.ne(PmTeam::getTeamId, teamId);
        }
        return baseMapper.selectCount(lqw) == 0;
    }

    /**
     * 检查团队名称是否唯一
     */
    @Override
    public Boolean checkTeamNameUnique(String teamName, Long teamId) {
        LambdaQueryWrapper<PmTeam> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeam::getTeamName, teamName);
        if (teamId != null) {
            lqw.ne(PmTeam::getTeamId, teamId);
        }
        return baseMapper.selectCount(lqw) == 0;
    }
}
